import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/models/qr_statistics.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/reportForm/reportTableQr/report_table_qr_detail_page.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/calendar_bar.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/shadow_radius_card.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:router/annotation.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:async/async.dart';

@RouterConfig(ReportTableQrPage.pageName)
class ReportTableQrPage extends StatefulWidget {
  static const pageName = '/ReportTableQrPage';

  @override
  _ReportTableQrPageState createState() => _ReportTableQrPageState();
}

class _ReportTableQrPageState extends BaseState<ReportTableQrPage> {
  _ReportTableQrPageState() : super(ReportTableQrPage.pageName);
  DateTime startTime;
  DateTime endTime;

  QrStatistics data;

  @override
  void initState() {
    super.initState();

    final now = DateTime.now();
    startTime = DateUtils.startOfTheDay(now);
    endTime = DateUtils.endOfTheDay(now);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '台卡收款统计',
        actions: [
          LabelButton(
            title: '明细',
            padding: EdgeInsets.only(top: 2, bottom: 2, left: 8),
            onTap: navDetail,
          )
        ],
      ),
      body: Loader<QrStatistics>(
        loadTask: loadTask,
        builder: (context) {
          return SingleChildScrollView(
            padding: EdgeInsets.all(30.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Row(
                    children: [
                      Expanded(
                        child: CalendarBar(
                          startDateTime: startTime,
                          endDateTime: endTime,
                          onDateTimeChanged: (List<DateTime> dateTime) {
                            setState(() {
                              startTime = dateTime[0];
                              endTime = dateTime[1];
                            });

                            refresh();
                          },
                          type: CalendarType.ymdhm,
                        ),
                      ),
                    ],
                  ),
                  margin: EdgeInsets.only(bottom: 30.w),
                ),
                RichText(
                  text: TextSpan(
                    text: '台卡统计',
                    style: TextStyleConstant().normal_1_36,
                    children: [
                      TextSpan(text: '  如若设置了营业时间，则以营业时间为准', style: TextStyleConstant().normal_3_24),
                    ],
                  ),
                ),
                Container(
                  height: 230.w,
                  margin: EdgeInsets.only(top: 30.w),
                  decoration: BoxDecoration(
                      gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
                        const Color(0xFF4F53F6),
                        const Color(0xFF5770F6),
                      ]),
                      borderRadius: BorderRadius.circular(14)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      buildTopCartItem(AmountUtil.price2String(data.totalFee), '收款总额', '元'),
                      Container(
                        width: 1.px,
                        height: 40.w,
                        color: Colors.white.withOpacity(0.5),
                      ),
                      buildTopCartItem(data.countOrder.toString(), '交易笔数', '单'),
                    ],
                  ),
                ),
                buildCard(
                  icon: 'assets/image/report_qr_wx.png',
                  title: '微信',
                  totalFee: data.wechatTotalFee,
                  countOrder: data.wechatPayCountOrder,
                  refundCountOrder: data.wechatRefundCountOrder,
                ),
                buildCard(
                  icon: 'assets/image/report_qr_al.png',
                  title: '支付宝',
                  totalFee: data.alipayTotalFee,
                  countOrder: data.alipayPayCountOrder,
                  refundCountOrder: data.alipayRefundCountOrder,
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget buildCard({String icon, String title, int totalFee, int countOrder, int refundCountOrder}) {
    return ShadowRadiusCard(
      margin: EdgeInsets.only(top: 30.w),
      child: Column(
        children: [
          Row(
            children: [
              Container(
                width: 105.w,
                alignment: Alignment.center,
                child: BaseImage(
                  icon,
                  width: 56.w,
                  height: 56.w,
                ),
              ),
              Expanded(
                child: Container(
                  height: 100.w,
                  alignment: Alignment.centerLeft,
                  decoration: BoxDecoration(border: Border(bottom: BorderSide(color: ColorConstant.e5e5, width: 1.px))),
                  child: Text(title, style: TextStyleConstant().normal_1_28),
                ),
              ),
            ],
          ),
          buildRow('收款总额', AmountUtil.price2String(totalFee)),
          buildRow('收款成功笔数', '$countOrder'),
          buildRow('退款成功笔数', '$refundCountOrder'),
        ],
      ),
    );
  }

  Widget buildRow(String title, String value) {
    return Container(
      height: 100.w,
      padding: EdgeInsets.only(left: 105.w, right: 25.w),
      child: Container(
        decoration: BoxDecoration(border: Border(bottom: BorderSide(color: ColorConstant.e5e5, width: 1.px))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(title, style: TextStyleConstant().normal_2_26),
            Text(value, style: TextStyleConstant().normal_1_26),
          ],
        ),
      ),
    );
  }

  Widget buildTopCartItem(String top, String desc, String unit) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(top, style: TextStyleConstant().white_40.copyWith(fontFamily: 'DINAlternate-Bold', fontWeight: FontWeight.bold)),
        Container(
          margin: EdgeInsets.only(top: 20.w),
          child: RichText(
            text: TextSpan(
                text: '$desc/',
                style: TextStyleConstant().white_24.copyWith(color: Colors.white.withOpacity(0.8)),
                children: [TextSpan(text: unit, style: TextStyleConstant().yellow_22)]),
          ),
        ),
      ],
    );
  }

  Future<Result<QrStatistics>> loadTask() async {
    final res = await api.queryReportTableQr(formatDatTime2String(startTime), formatDatTime2String(endTime));
    if (!res.successful()) {
      return Result.error(res.msg);
    }

    data = res.data;

    return Result.value(res.data);
  }

  String formatDatTime2String(DateTime dateTime) {
    return flustars.DateUtil.formatDate(dateTime);
  }

  void refresh() async {
    try {
      showLoadingToast();

      await loadTask();

      setState(() {});
    } finally {
      hideLoadingToast();
    }
  }

  void navDetail() {
    Navigator.pushNamed(context, ReportTableQrDetailPage.pageName);
  }
}
